package com.linx.rxlife

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import io.reactivex.SingleSource
import io.reactivex.functions.Consumer
import io.reactivex.internal.functions.Functions
import io.reactivex.internal.observers.ConsumerSingleObserver

class SingleLife<T>(
    private val singleSource: SingleSource<T>,
    owner: LifecycleOwner,
    atLeastState: Lifecycle.State = Lifecycle.State.STARTED
) : RxLife(owner, atLeastState) {

    private lateinit var onSuccess: Consumer<in T>
    private lateinit var onError: Consumer<in Throwable>

    override fun onActive() {
        val observer = ConsumerSingleObserver(
            onSuccess, onError
        )
        singleSource.subscribe(observer)
        disposable = observer
    }

    fun observe(
        onSuccess: Consumer<in T>,
        onError: Consumer<in Throwable> = Functions.ON_ERROR_MISSING
    ) {
        if (owner.lifecycle.currentState != Lifecycle.State.DESTROYED) {
            owner.lifecycle.addObserver(this)
            this.onSuccess = onSuccess
            this.onError = onError
            activeStateChange(shouldBeActive())
        }
    }

}